<?php
/**
 * Created by PhpStorm.
 * User: gqc
 * Date: 2017/3/15
 * Time: 10:19
 */
namespace Inbound\Service;
class SingleShipmentidGrabService extends PublicInfoService
{

    public $Inboundshipmentplandetail = NULL;
    public $shipToAddressService = NULL;

    /**
     * SingleShipmentidGrabService constructor.
     * @param string $table
     * @param array $param
     * 初始化Model
     */
    public function __construct($table = '',$param = array()) {
        $this->shipToAddressService = D('Api/Amazon/ShipToAddress','Service');
        $this->Inboundshipmentplandetail = D('Inboundshipmentplandetail','Model');
        $this->Inboundshipmentplan       = D('Inboundshipmentplan','Model');
    }

    /**
     * @param $accountId
     * @param $destinationFulfillmentCenterId
     * 根据账号ID和目的仓唯一标示判断地址是否存在
     */
    public function destinationFulfillmentCenterAddress ($accountId, $destinationFulfillmentCenterId) {
        return $this->shipToAddressService->checkSiteCenterId($accountId, $destinationFulfillmentCenterId);
    }

    /**
     * @param $accountId
     * @param $inboundShipmentItems
     * @return array
     * 根据抓取的和备货申请的进行对比
     */
    public function matchNeedsApply ($accountId, $inboundShipmentItems) {
        $shipmentItems = array();
        $isShipmentOk = 1;
        $siteId = 0;
        foreach ($inboundShipmentItems as $item) {
            $shipmentItems[$item['SellerSKU']]['seller_sku'] = $item['SellerSKU'];
            $shipmentItems[$item['SellerSKU']]['fnsku'] = $item['FulfillmentNetworkSKU'];
            $shipmentItems[$item['SellerSKU']]['quantity'] = $item['QuantityShipped'];
        }

        $enterpriseDominants = PublicInfoService::get_company_array();
        $accountSellerSkuInfo = PublicInfoService::accountSellerSkuInfoGet($accountId, array_keys($shipmentItems));

        $isAllSingleShip = 0;
        foreach ($shipmentItems as $sellerSku=>&$item) {
            $item['exceptionCode'] = 0;
            $item['exceptionMsg'] = '';

            if(empty($accountSellerSkuInfo[$sellerSku]['private_sku'])) {
                $item['sku'] = '';
                $item['exception'] = 1;
                $item['exceptionMsg'] = $sellerSku . "没有录入系统或者没有启用<br/>";
            } else {
                $item['sku'] = $accountSellerSkuInfo[$sellerSku]['private_sku'];
            }

            if(empty($accountSellerSkuInfo[$sellerSku]['title'])) {
                $item['title'] = '';
                $item['exception'] = 1;
                $item['exceptionMsg'] .= $sellerSku . "的title为空<br/>";
            } else {
                $item['title'] = $accountSellerSkuInfo[$sellerSku]['title'];
            }

            $item['asin'] = isset($accountSellerSkuInfo[$sellerSku]['asin']) ? $accountSellerSkuInfo[$sellerSku]['asin'] : '';

            if(!empty($item['sku'])) {
                $conditions = array(
//                    'create_time' => array('EGT', date("Y-m-d H:i:s",strtotime('-10 day'))),
                    'account_id' => $accountId,
                    'sku' => $item['sku'],
                    'seller_sku' => $sellerSku,
                    'needs_quantity' => $item['quantity'],
                    'status' => 30,
                );

                $needsInfo = M("fba_prepare_needs_details", ' ', 'DB_FBAERP')
                    ->where($conditions)
                    ->field('id, sku_name, site_id, single_ship, export_tax_rebate, claim_arrive_time, enterprise_dominant, create_time, hs_code, declaration_element, sku_cname')
                    ->order('claim_arrive_time asc')
                    ->select();

                if(empty($needsInfo)) {
                    $item['exception'] = 1;
                    $item['exceptionMsg'] .= $sellerSku . "待平台计划的需求不存在，以下原因之一：1.没有备货需求申请；2.备货申请里的sellerSku、数量和亚马逊后台对不上；3.物流部没有预审；4.备货申请时间超过10天.<br/>";
                } else {
                    $currentSkuNeedCount = 0;
                    foreach ($needsInfo as $need) {
                        if($need['single_ship']) {
                            $item['single_ship'] = 1;
                        }
                        if($need['single_ship'] && count($inboundShipmentItems) > 1) {
                            if($isAllSingleShip === false) {
                                $isAllSingleShip = 2;
                                $item['exception'] = 1;
                                $item['exceptionMsg'] .= $sellerSku . "含有单独和非单独发货商品，请单独下备货计划<br/>";
                                break;
                            }
                            $isAllSingleShip = 1;
                        } elseif($isAllSingleShip == 1 || $isAllSingleShip == 2) {
                            $isAllSingleShip = 2;
                            $item['exception'] = 1;
                            $item['exceptionMsg'] .= $sellerSku . "含有单独和非单独发货商品，请单独下备货计划<br/>";
                            break;
                        } else {
                            $isAllSingleShip = false;
                        }
//                        if($need['single_ship'] && count($inboundShipmentItems) > 1) {
//                            $item['exception'] = 1;
//                            $item['exceptionMsg'] .= $sellerSku . "需要单独发货，请单独下备货计划<br/>";
//                            break;
//                        } else {
                            $currentSkuNeedCount ++;
                            $item['connectNeedsDetailId'][] = $need['id'];
                            $item['sku_name'] = $need['sku_name'];
                            $siteId = $need['site_id'];

                            $item['hs_code'] = $need['hs_code'];
                            $item['declaration_element'] = $need['declaration_element'];
                            $item['sku_cname'] = $need['sku_cname'];
                            $item['radios'][$need['id']] = array(
                                'claim_arrive_time' => $need['claim_arrive_time'],
                                'export_tax_rebate' => $need['export_tax_rebate'],
                                'enterprise_dominant' => $need['enterprise_dominant'],
                                'value' => $need['id'],
                                'valueStr' => $item['sku'] . '，' . $sellerSku . '，' .
                                ($need['export_tax_rebate'] == 1 ? '出口退税，' : '非出口退税，') .
                                $enterpriseDominants[$need['enterprise_dominant']] .
                                '，要求到货日期：' . $need['claim_arrive_time'] .
                                    '，需求申请时间：' . $need['create_time'],
                            );
                        //}
                    }
                    $item['needsCount'] = $currentSkuNeedCount;
                }
            }

            $item['exception'] == 1 && $isShipmentOk = 0;
        }

        return array_merge($shipmentItems, array('ok' => $isShipmentOk, 'site_id' => $siteId));
    }

    /**
     * @param $inboundShipmentsData
     * @param $inboundShipmentItems
     * @param null $model
     * @return int
     * 增加抓取Shipmentid到数据库
     */
    public function addGrabShipmentid($inboundShipmentsData, &$inboundShipmentItems, &$model = NULL) {
        $model = $model==NULL?$this->Inboundshipmentplandetail->model:$model;

        $this->Inboundshipmentplandetail->add_by_table($inboundShipmentsData,$model);
        if($inboundShipmentPlanId = $this->Inboundshipmentplandetail->Inboundshipmentplan_id){
            $needsDetailIds = array();
            foreach ($inboundShipmentItems as $item) {
                $needDetailId = $item['needDetailId'];
                unset($item['needDetailId']);
                $item['inbound_shipment_plan_id'] = $inboundShipmentPlanId;
                $this->Inboundshipmentplandetail->add_detail_by_table($item, $model);
                $relationship = array(
                    'prepare_needs_details_id' => $needDetailId,
                    'shipmentid'               => $inboundShipmentsData['shipmentid'],
                    'plan_num'                 => $item['quantity'],
                    'status'                   => 10
                );
                D('Prepareneeds','Service')->insert_prepare_needs_details_shipmentid($relationship);

                $needsDetailIds[] = $needDetailId;
            }

            D('Prepareneedsdetail','Model')->prepareNeedsDetails->where(array('id'=>array('IN', $needsDetailIds)))->save(array('status' => 80));
        }

        if($this->Inboundshipmentplandetail->Inboundshipmentplandetail_id) {
            $model->commit();
        } else {
            $model->rollback();
        }

        return 200;
    }
}